package cluster.clustersingleton

import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory

/**
  * Created by shouf on 2016/5/19.
  * //測試1
curl -X GET -H "Content-Type: application/json" -H "Cache-Control: no-cache" "http://127.0.0.1:9000/api/v1/posts/ABC"
//測試2
curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{
  "text": "哩哩扣扣"
}' "http://127.0.0.1:9000/api/v1/posts"

  */
object AkkaHttpMicroservice extends App with RestInterface {
  val port = if (args.isEmpty) 0 else args(0).toInt
//  val config = ConfigFactory.parseString(s"akka.remote.netty.tcp.port=${port}").
//    withFallback(ConfigFactory.load().getConfig("cluster"))

  val config = ConfigFactory.parseString(
    """ akka {
        loglevel = DEBUG
      }"""
  )

  implicit val system = ActorSystem("clusterSys", config)
  override implicit val executor = system.dispatcher
  override implicit val materializer = ActorMaterializer()
  override val logger = Logging(system, getClass)

  val host = "127.0.0.1"
  val binding = Http().bindAndHandle(routes, host, port)
  //  map { binding =>
  //    println(s"REST interface bound to $host:$port") } recover { case ex =>
  //    println(s"REST interface could not bind to $host:$port", ex.getMessage)
  //  }

  logger.info(s"Bound to port $port on host $host")
  binding onFailure {
    case ex: Exception ⇒
      logger.error(s"Failed to bind to $host:$port!", ex)
  }
  sys.addShutdownHook(system.terminate)
}
